import { Login, Logout } from "@/api/Login";

const initState = JSON.parse(localStorage.getItem("user") || "{}");
const musiclist = JSON.parse(localStorage.getItem("musicList") || "[]");

const state = {
	user: initState,
	isLogin: false,
	musicList: musiclist,
};
const actions = {
	async login({ commit }, { pho, pas }) {
		const data = await Login(pho, pas);
		const user = {
			id: data.account.id,
			token: data.token,
		};
		commit("LOGIN", user);
	},
	async logout({ commit }) {
		await Logout();
		commit("LOGOUT");
	},
	isloginshow({ commit }, isShow) {
		commit("ISLOGINSHOW", isShow);
	},
	musiclist({ commit }, idlist) {
		commit("MUSICLIST", idlist);
	},
	delmusic({ commit }, index) {
		commit("DELMUSIC", index);
	},
	delmusicall({ commit }) {
		commit("DELMUSICALL");
	},
};
const mutations = {
	// 登录
	LOGIN(state, user) {
		// 存储在localStorage中
		localStorage.setItem("user", JSON.stringify(user));
		// 存储在vuex中
		state.user.id = user.id;
		state.user.token = user.token;
		state.isLogin = false;
	},
	// 退出登录
	LOGOUT(state) {
		localStorage.removeItem("user");
		// 清空vuex数据
		state.user.id = "";
		state.user.nickName = "";
		state.user.token = "";
	},
	// 显示登录页面
	ISLOGINSHOW(state, isShow) {
		state.isLogin = isShow;
	},
	// 添加歌曲列表到播放列表
	MUSICLIST(state, idList) {
		state.musicList = JSON.parse(JSON.stringify(idList));
		localStorage.setItem("musicList", JSON.stringify(state.musicList));
	},

	// 从播放列表删除歌曲
	DELMUSIC(state, id) {
		state.musicList = state.musicList.splice(id, 1);
		localStorage.setItem("musicList", JSON.stringify(state.musicList));
	},

	// 清空播放列表
	DELMUSICALL(state) {
		state.musicList = [];
		localStorage.setItem("musicList", JSON.stringify(state.musicList));
	},

	// 播放歌曲
	IMMEDIATELTY(state, id) {
		state.musicList.unshift(id);
		localStorage.setItem("musicList", JSON.stringify(state.musicList));
	},
};

export default {
	namespaced: true,
	state,
	actions,
	mutations,
};
